﻿using System.Reflection;
using NLite.Internal;

namespace NLite.Reflection
{
	
	delegate object Getter(object target);

	/// <summary>
	/// 
	/// </summary>
	public static class GetterExtensions
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="member"></param>
		/// <param name="target"></param>
		/// <returns></returns>
		public static object Get(this MemberInfo member, object target)
		{

			if (target != null && target.GetType().IsValueType)
			{
				switch (member.MemberType)
				{
						case MemberTypes.Field: return (member as FieldInfo).GetValue(target); break;
						case MemberTypes.Property: return (member as PropertyInfo).GetValue(target, null); break;
						case MemberTypes.Method: return (member as MethodInfo).Invoke(target, new object[0]); break;
				}

				return null;
			}
			else
			{
				try
				{
					return DynamicMethodFactoryProxy.Instance.CreateGetter(member)(target);
				}
				catch (TargetInvocationException ex)
				{
					
					throw ex.InnerException;
				}
				
			}
		}
	}
}
